package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Role;
import cn.hd01.repository.entity.User;
import cn.hd01.service.RoleService;
import cn.hd01.service.UserService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebException;
import cn.hd01.web.util.WebHelper;

@Controller
@RequestMapping("/user")
@Auth
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@RequestMapping(path = {"/", ""}, method = RequestMethod.GET)
	public String index(Model m) {
		m.addAttribute("roles", roleService.findAll());
		return "user";
	}

	@ResponseBody
	@RequestMapping(path = "/modifyPwd", method = RequestMethod.POST)
	public void modify(String oldPwd, String newPwd) {
		User u = userService.findOne(WebHelper.currentUser().getId());
		if (!u.getPassword().equals(oldPwd)) {
			throw new WebException(HttpStatus.NOT_ACCEPTABLE, "原密码错误");
		}
		userService.updatePassword(u.getId(), newPwd);
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<User> find(User u, @PageableDefault Pageable pageable) {
		return userService.findAdmin(u, pageable);
	}

	@ResponseBody
	@RequestMapping(path = "/resetPwd/{id}", method = RequestMethod.GET)
	private String resetPwd(@PathVariable("id") Integer id) {
		if (!userService.exists(id)) {
			throw new WebException(HttpStatus.NOT_ACCEPTABLE, "不存在该用户");
		}
		userService.updatePassword(id, WebConstant.DEFAULT_PASSWORD);
		return WebConstant.DEFAULT_PASSWORD;
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		userService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(User u) {

		Role role = roleService.findOne(u.getRoleId());
		u.setRoleName(role.getName());

		if (u.getId() == null) {
			if (userService.exists(u.getName())) {
				throw new WebException(HttpStatus.BAD_REQUEST, "用户名已经存在");
			}

			// 后台添加为后台用户类型
			u.setType(3);
			u.setPassword(WebConstant.DEFAULT_PASSWORD);
			userService.save(u);
			return;
		}

		userService.updateUser(u);
	}
}
